import { autoUpdater } from 'electron-updater'
import { app, BrowserWindow, ipcMain } from 'electron'

const uploadUrl = 'http://192.168.101.112:8080/electrons/'

const message = {
  checking: '正在检查更新...',
  error: '检查更新出错',
  updateAva: '检测到新版本，正在下载...',
  updateNotAva: '当前版本为最新版本'
}

const transfer = (text: string, mainWin: BrowserWindow) => {
  mainWin.webContents.send('update', text)
}

export const createAutoUpdater = (
  mainWin: BrowserWindow,
  download: string = uploadUrl
) => {
  autoUpdater.setFeedURL({
    url: download,
    provider: 'generic'
  })

  // Cancel automatic download
  autoUpdater.autoDownload = false

  autoUpdater.on('error', () => {
    transfer(message.error, mainWin)
  })

  autoUpdater.on('checking-for-update', () => {
    transfer(message.checking, mainWin)
  })

  autoUpdater.on('update-available', () => {
    transfer(message.updateAva, mainWin)
  })

  autoUpdater.on('update-not-available', () => {
    transfer(message.updateNotAva, mainWin)
  })

  autoUpdater.on('download-progress', (progress) => {
    mainWin.webContents.send('download-progress', progress)
  })

  autoUpdater.on('update-downloaded', () => {
    ipcMain.on('start-update', () => {
      autoUpdater.quitAndInstall()
    })
    mainWin.webContents.send('update-downloaded')
  })

  ipcMain.on('download-update', () => {
    autoUpdater.downloadUpdate()
  })

  ipcMain.on('check-updates', () => {
    if (mainWin) autoUpdater.checkForUpdates()
  })

  // Consider updating the program immediately
  if (app.isPackaged) {
    autoUpdater.checkForUpdates()
  }
}
